<template>
  <div class="common-container">
    <div class="common-header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="handleAdd">新增角色</el-button>
    </div>

    <el-card class="common-table-card">
      <el-table
        v-loading="loading"
        :data="roleList"
        border
        style="width: 100%"
        :height="tableHeight"
      >
        <el-table-column prop="id" label="角色ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="roleCode" label="角色编码" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button text type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button text type="primary" @click="handleAssignMenu(scope.row)">分配菜单</el-button>
            <el-button text type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="common-pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleForm.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="common-dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配菜单对话框 -->
    <el-dialog
      title="分配菜单权限"
      v-model="menuDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <span>{{ currentRole.roleName }}</span>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            ref="menuTreeRef"
            :data="menuTreeData"
            :props="{ label: 'name', children: 'children' }"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedMenuIds"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="common-dialog-footer">
          <el-button @click="menuDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMenuAssign">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllRoles, getRoleById, addRole, updateRole, deleteRole, assignMenus } from '../utils/api'
import { getMenuTree, getMenuTreeByRoleId } from '../utils/api'

export default {
  name: 'RoleManagement',
  setup() {
    // 角色列表数据
    const loading = ref(false)
    const roleList = ref([])
    const total = ref(0)
    const queryParams = reactive({
      pageNum: 1,
      pageSize: 10
    })
    
    // 计算表格高度
    const tableHeight = computed(() => {
      return 'calc(100vh - 250px)'
    })

    // 角色表单对话框
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const roleFormRef = ref(null)
    const roleForm = reactive({
      id: undefined,
      roleName: '',
      roleCode: '',
      description: '',
      status: 1
    })

    // 表单验证规则
    const rules = {
      roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
      roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
    }

    // 菜单分配对话框
    const menuDialogVisible = ref(false)
    const menuTreeRef = ref(null)
    const menuTreeData = ref([])
    const checkedMenuIds = ref([])
    const currentRole = ref({})

    // 获取角色列表
    const getList = async () => {
      loading.value = true
      try {
        const response = await getAllRoles()
        roleList.value = response.data.data
        total.value = roleList.value.length
      } catch (error) {
        console.error('获取角色列表失败', error)
      } finally {
        loading.value = false
      }
    }

    // 处理分页大小变化
    const handleSizeChange = (size) => {
      queryParams.pageSize = size
      getList()
    }

    // 处理页码变化
    const handleCurrentChange = (page) => {
      queryParams.pageNum = page
      getList()
    }

    // 新增角色
    const handleAdd = () => {
      resetForm()
      dialogTitle.value = '新增角色'
      dialogVisible.value = true
    }

    // 编辑角色
    const handleEdit = (row) => {
      resetForm()
      dialogTitle.value = '编辑角色'
      getRoleById(row.id).then(response => {
        Object.assign(roleForm, response.data.data)
        dialogVisible.value = true
      })
    }

    // 删除角色
    const handleDelete = (row) => {
      ElMessageBox.confirm('确认删除该角色吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(row.id).then(() => {
          ElMessage.success('删除成功')
          getList()
        })
      }).catch(() => {})
    }

    // 分配菜单
    const handleAssignMenu = async (row) => {
      currentRole.value = row
      menuDialogVisible.value = true
      
      try {
        // 获取所有菜单树
        const menuResponse = await getMenuTree()
        menuTreeData.value = menuResponse.data.data
        
        // 获取角色已分配的菜单ID
        const roleMenuResponse = await getMenuTreeByRoleId(row.id)
        checkedMenuIds.value = roleMenuResponse.data.data.map(item => item.id)
      } catch (error) {
        console.error('获取菜单数据失败', error)
      }
    }

    // 提交菜单分配
    const submitMenuAssign = async () => {
      const checkedKeys = menuTreeRef.value.getCheckedKeys()
      const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
      const menuIds = [...checkedKeys, ...halfCheckedKeys]
      
      try {
        await assignMenus(currentRole.value.id, menuIds)
        ElMessage.success('分配菜单权限成功')
        menuDialogVisible.value = false
      } catch (error) {
        console.error('分配菜单权限失败', error)
      }
    }

    // 重置表单
    const resetForm = () => {
      roleForm.id = undefined
      roleForm.roleName = ''
      roleForm.roleCode = ''
      roleForm.description = ''
      roleForm.status = 1
    }

    // 提交表单
    const submitForm = () => {
      roleFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (roleForm.id) {
              await updateRole(roleForm)
              ElMessage.success('修改成功')
            } else {
              await addRole(roleForm)
              ElMessage.success('新增成功')
            }
            dialogVisible.value = false
            getList()
          } catch (error) {
            console.error('保存角色失败', error)
          }
        }
      })
    }

    onMounted(() => {
      getList()
    })

    return {
      loading,
      roleList,
      total,
      queryParams,
      dialogVisible,
      dialogTitle,
      roleForm,
      roleFormRef,
      rules,
      menuDialogVisible,
      menuTreeRef,
      menuTreeData,
      checkedMenuIds,
      currentRole,
      tableHeight,
      getList,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleAssignMenu,
      submitMenuAssign,
      submitForm
    }
  }
}
</script>

<style scoped>

</style>